<?php


namespace app\common\service;


use app\common\util\MailUtil;
use app\common\validate\CommonValidate;
use think\exception\ValidateException;
use think\facade\Request;

class SystemService
{
    public static function sendEmail()
    {
        $data = Request::post();
        $rule = [
            'address' => 'require',
            'title' => 'require',
            'content' => 'require',
        ];
        $message = [
            'address.require' => "收件人不能为空",
            'title.require' => "邮件标题不能为空",
            'content.require' => "邮件内容不能为空",
        ];
        $check = Request::checkToken('__token__', $data);
        if (false === $check) {
            throw new ValidateException('invalid token');
        }
        if (($msg = CommonValidate::check($rule, $message, $data)) !== true)
            return ['msg' => $msg, 'code' => 201];
        foreach ($data as $key => $value) {
            if (strstr($key, 'file') !== false && strstr($key, 'name_file') == false) {
                $indexArr = explode('[', $key);
                $index = $indexArr[1] ?? '';
                $index = explode(']', $index)[0];

                $data['file'][] = [
                    'file' => root_path() . 'public' . dealImage($value, 0),
                    'file_name' => $data["name_file[$index]"],
                ];
                unset($data[$key]);
                unset($data["name_file[$index]"]);
            }
        }
        $ret = MailUtil::go($data['address'], $data['title'], $data['content'], $data['file'] ?? []);
        return ['code' => (int)$ret['code'], 'msg' => $ret['msg']];
    }
}